import pymysql
from itemadapter import ItemAdapter

class ScrapytestPipeline:
    def process_item(self, item, spider):
        return item

class DoubanPipeline(ScrapytestPipeline):
    def __init__(self):
        ## 创建数据库链接
        hostid = "localhost"  # 数据库主机地，本机MySQL的为localhost
        username = "root"  # 数据库用户名
        password = "liuyaoxi2004"  # 数据库密码
        self.mydb = pymysql.connect(host=str(hostid), user=str(username), passwd=str(password))
        ## 获得操作游标
        self.mycursor = self.mydb.cursor()
        print("连接数据库成功")
    def process_item(self, item, spider):
        # sql语句
        insert_sql = """
        insert into scrapytest.quotes (Mid, `name`, movieMakers, Myear, Mcountry, Mtype, star, score, comments, `desc`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
        """
        # 执行插入数据到数据库操作
        self.mycursor.execute(insert_sql, (item['Mid'], item['name'], item['movieMakers'], item['Myear'], item['Mcountry'], item['Mtype'], item['star'], item['score'], item['comments'], item['desc']))
        # 提交，不进行提交无法保存到数据库
        self.mydb.commit()
    def close_spider(self, spider):
        # 关闭游标和连接
        self.mycursor.close()
        self.mydb.close()
